//
//  PLCategoryView.m
//  PerfectLifeTwo
//
//  Created by 黄华强 on 2018/3/1.
//  Copyright © 2018年 PerfectLife. All rights reserved.
//

#import "PLCategoryView.h"

#import "PLCategoryViewCell.h"

@interface PLCategoryView()<UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic,strong) UICollectionView *collectionView;

@end

static NSString * const cellId = @"cellId";

@implementation PLCategoryView

- (instancetype)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    
    if (self) {
        
        self.columns = 4;
    }
    return self;
}


#pragma mark - collectionView代理方法

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.itemInfoArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    PLCategoryViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
    
    NSDictionary *itemDict = self.itemInfoArray[indexPath.item];
    
    [cell.cellImageView sd_setImageWithURL:[NSURL URLWithString:itemDict[@"image"]] placeholderImage:[UIImage imageNamed:itemDict[@"image"]]];
    cell.cellTitleLabel.text = itemDict[@"title"];
    
    if (self.titleColor) {
        cell.cellTitleLabel.textColor = self.titleColor;
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.selectedItemBlock) {
        self.selectedItemBlock(indexPath.item);
    }
    
}

#pragma mark - set方法

- (void)setItemInfoArray:(NSArray<NSDictionary *> *)itemInfoArray {
    
    _itemInfoArray = itemInfoArray;
    
    if (itemInfoArray.count > 0 && !_collectionView) {
        [self addSubview:self.collectionView];
    }
    
    [self.collectionView reloadData];
}


#pragma mark - 懒加载

- (UICollectionView *)collectionView {
    
    if (!_collectionView) {
        
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        
        CGSize viewSize = self.frame.size;
        
        flowLayout.itemSize = CGSizeMake(viewSize.width / self.columns, viewSize.height);
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:flowLayout];
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.dataSource = self;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.pagingEnabled = YES;
        [_collectionView registerClass:[PLCategoryViewCell class] forCellWithReuseIdentifier:cellId];
        
    }
    
    return _collectionView;
}

@end
